此多邊形方法雖然不是小畫家的畫法,但一樣可以達成多邊形的做法,如下:
/**
* 滑鼠點下畫布
*/
const handleMouseDown = (event: any) => {
...
switch (tool) {
case "polygon":
pointsArray = [...pointsArray, point];
drawPolygon({ ctx });
break;
}
};
/** 繪製多邊形 */
const drawPolygon = ({ ctx }: { ctx: CanvasRenderingContext2D }) => {
clearCanvas();
ctx.beginPath();
ctx.moveTo(pointsArray[0].x, pointsArray[0].y);
for (let index = 1; index < pointsArray.length; index++) {
ctx.lineTo(pointsArray[index].x, pointsArray[index].y);
}
ctx.closePath();
ctx.stroke();
};